﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ValidationFramework.ErrorMessage
{
	public class ErrorMessageResolver
	{
		public string ResolvePropertyErrorMessage(PropertyStateRule rule, object attemptedValue, PropertyMessageContext context)
		{
			// Use message provider by consumer
			if (!string.IsNullOrEmpty(rule.ErrorMessage))
				return rule.ErrorMessage;

			// TODO: Get error message provider working. Make sure this also works on the other error message resolver methods
			// Use message provided by the specified ErrorMessageProvider
			//if (rule.UseErrorProvider)
			//{
			//    if (ConfigurationService.ErrorMessageProvider == null)
			//    {
			//        throw new InvalidOperationException("useErrorMessageProvider is true but no ErrorMessageProvider is specified in the ConfigurationService.");
			//    }
			//    return ConfigurationService.ErrorMessageProvider.GetErrorMessage(rule.Validator, context);
			//}

			// Use the validator's default message
			var defaultMessage = rule.Validator.GetDefaultErrorMessage(context);
			if (!string.IsNullOrEmpty(defaultMessage))
			{
				return defaultMessage;
			}

			// If all else fails, use a standard default
			return string.Format("The property {0} on type {1} is invalid", context.PropertyName, context.TypeName);
		}
		public string ResolvePropertyErrorMessage(PropertyValueRule rule, object attemptedValue, PropertyMessageContext context)
		{
			// Use message provider by consumer
			if (!string.IsNullOrEmpty(rule.ErrorMessage))
				return rule.ErrorMessage;

			// Use the validator's default message
			var defaultMessage = rule.Validator.GetDefaultPropertyErrorMessage(context);
			if (!string.IsNullOrEmpty(defaultMessage))
			{
				return defaultMessage;
			}

			// If all else fails, use a standard default
			return string.Format("The property {0} on type {1} is invalid", context.PropertyName, context.TypeName);
		}
		public string ResolveParameterErrorMessage(ParameterRule rule, object attemptedValue, ParamMessageContext context)
		{
			// Use message provider by consumer
			if (!string.IsNullOrEmpty(rule.ErrorMessage))
				return rule.ErrorMessage;

			// Use the validator's default message
			var defaultMessage = rule.Validator.GetDefaultParamErrorMessage(context);
			if (!string.IsNullOrEmpty(defaultMessage))
			{
				return defaultMessage;
			}

			// If all else fails, use a standard default
			return string.Format("The parameter {0} of method {1} on type {2} is invalid", context.ParameterName, context.MethodName, context.TypeName);
		}

	}
}
